package com.example.show_auto.data

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

// 创建DataStore实例
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "app_preferences")

/**
 * 数据持久化管理器
 */
class DataStoreManager(private val context: Context) {
    
    companion object {
        // 定义键
        private val CODE_VALID_KEY = booleanPreferencesKey("code_valid")
        private val PERSONAL_DATA_KEY = stringPreferencesKey("personal_data")
        private val VALIDATION_CODE_KEY = stringPreferencesKey("validation_code")
    }
    
    /**
     * 保存校验码状态
     */
    suspend fun saveCodeValidation(isValid: Boolean, code: String = "") {
        context.dataStore.edit { preferences ->
            preferences[CODE_VALID_KEY] = isValid
            if (code.isNotEmpty()) {
                preferences[VALIDATION_CODE_KEY] = code
            }
        }
    }
    
    /**
     * 获取校验码状态
     */
    fun getCodeValidation(): Flow<Boolean> {
        return context.dataStore.data.map { preferences ->
            preferences[CODE_VALID_KEY] ?: false
        }
    }
    
    /**
     * 获取保存的校验码
     */
    fun getValidationCode(): Flow<String> {
        return context.dataStore.data.map { preferences ->
            preferences[VALIDATION_CODE_KEY] ?: ""
        }
    }
    
    /**
     * 保存个人数据
     */
    suspend fun savePersonalData(personalDataJson: String) {
        context.dataStore.edit { preferences ->
            preferences[PERSONAL_DATA_KEY] = personalDataJson
        }
    }
    
    /**
     * 获取个人数据
     */
    fun getPersonalData(): Flow<String> {
        return context.dataStore.data.map { preferences ->
            preferences[PERSONAL_DATA_KEY] ?: ""
        }
    }
    
    /**
     * 清除所有数据
     */
    suspend fun clearAll() {
        context.dataStore.edit { preferences ->
            preferences.clear()
        }
    }
}
